package com.fmsz.xmly.widget;

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.fmsz.xmly.R;

import static java.lang.Thread.sleep;

/**
 * Created by Administrator on 2016/12/8.
 */

public class CustomRefreshLayout extends LinearLayout implements View.OnTouchListener {

    private ListView listView;
    private View header;
    private int touchSlop;
    private ImageView arrow;
    private ProgressBar progressBar;
    private TextView refresh_des;
    private boolean loadOnce;//是否已经加载过一次
    private int hideHeaderHeight;
    private MarginLayoutParams marginParams;
    private boolean isTop;//listView是否到达顶部
    private float downY;
    private float yMove;
    private final int PULL_REFRESH = 0;//下拉状态
    private final int REFRESHING = 2;//正在刷新
    private final int RELEASE_TO_REFRESH = 1;//准备刷新状态
    public static final int REFRESH_FINISHED = 3;
    private int currentStatus = REFRESH_FINISHED;
    private boolean ableToPull;
    private int lastStatus;

    public CustomRefreshLayout(Context context) {
        super(context);
    }

    public CustomRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        header = LayoutInflater.from(context).inflate(R.layout.refresh_head, null, true);
        arrow = ((ImageView) header.findViewById(R.id.refresh_icon));
        progressBar = ((ProgressBar) header.findViewById(R.id.refresh_progress));
        refresh_des = ((TextView) header.findViewById(R.id.refresh_tv));
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        setOrientation(VERTICAL);
        addView(header, 0);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed && !loadOnce) {
            hideHeaderHeight = -header.getHeight();
            marginParams = ((MarginLayoutParams) header.getLayoutParams());
            marginParams.topMargin = hideHeaderHeight;
            listView = ((ListView) getChildAt(1));
            listView.setOnTouchListener(this);
            loadOnce = true;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        setIsAbleToPull(event);
        if (ableToPull) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downY = event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    yMove = event.getRawY();
                    int distance = ((int) (yMove - downY));
                    //如果是向下滑动并且下拉头完全隐藏屏蔽下拉事件
                    if (distance <= 0 && marginParams.topMargin <= hideHeaderHeight) {
                        return false;
                    }
                    if (distance < touchSlop) {
                        return false;
                    }
                    if (currentStatus != REFRESHING) {
                        if (marginParams.topMargin > 0) {
                            currentStatus = RELEASE_TO_REFRESH;
                        } else {
                            currentStatus = PULL_REFRESH;
                        }
                        marginParams.topMargin = (distance / 2) + hideHeaderHeight;
                        header.setLayoutParams(marginParams);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                default:
                    if (currentStatus == RELEASE_TO_REFRESH) {
                        // 松手时如果是释放立即刷新状态，就去调用正在刷新的任务

                    } else if (currentStatus == PULL_REFRESH) {
                        // 松手时如果是下拉状态，就去调用隐藏下拉头的任务

                    }
                    break;
            }
            if (currentStatus == PULL_REFRESH || currentStatus == RELEASE_TO_REFRESH) {
                updateHeaderView();
                listView.setFocusable(false);
                listView.setFocusableInTouchMode(false);
                listView.setPressed(false);
                lastStatus = currentStatus;
                return true;
            }
        }
        return false;
    }

    private void setIsAbleToPull(MotionEvent event) {
        View firstChild = listView.getChildAt(0);
        if (firstChild != null) {
            int firstVisiblePosition = listView.getFirstVisiblePosition();
            if (firstVisiblePosition == 0 && firstChild.getTop() == 0) {//到达顶部
                if (!ableToPull) {
                    downY = event.getRawY();
                }
                ableToPull = true;
            } else {//未到达顶部
                if (marginParams.topMargin != hideHeaderHeight) {
                    marginParams.topMargin = hideHeaderHeight;
                    header.setLayoutParams(marginParams);
                }
                ableToPull = false;
            }
        } else {
            ableToPull = true;
        }
    }

    private void updateHeaderView() {
        if (lastStatus != currentStatus) {
            if (currentStatus == PULL_REFRESH) {
                arrow.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
                rotateArrow();
            } else if (currentStatus == RELEASE_TO_REFRESH) {
                arrow.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
                rotateArrow();
            } else if (currentStatus == REFRESHING) {
                arrow.clearAnimation();
                arrow.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
            }
        }
    }

    private void rotateArrow() {
        float pivotX = arrow.getWidth() / 2f;
        float pivotY = arrow.getHeight() / 2f;
        float fromDegrees = 0f;
        float toDegrees = 0f;
        if (currentStatus == PULL_REFRESH) {
            fromDegrees = 180f;
            toDegrees = 360f;
        } else if (currentStatus == RELEASE_TO_REFRESH) {
            fromDegrees = 0f;
            toDegrees = 180f;
        }
        RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY);
        animation.setDuration(100);
        animation.setFillAfter(true);
        arrow.startAnimation(animation);
    }

    public interface OnRefreshListener {
        void onRefresh();
    }


}
